package br.com.monise.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import br.com.monise.model.Aprendiz;
import br.com.monise.model.Avaliacao;
import br.com.monise.model.Recurso;
import br.com.monise.util.GenericDao;

public class AvaliacaoDAO extends GenericDao<Avaliacao> {
	
	public Avaliacao getAvaliacaoRecursoaprendiz(Aprendiz aprendiz, Recurso recurso){
		EntityManager manager = getEntityManager();
		
		manager.getTransaction().begin();
        Query query = manager.createQuery("select a from Avaliacao a where a.recurso.idRecurso = :recurso and a.aprendiz.idAprendiz = :aprendiz");
		query.setParameter("aprendiz", aprendiz.getIdAprendiz());
		query.setParameter("recurso", recurso.getIdRecurso());

	    Avaliacao avaliacao = (Avaliacao) query.getSingleResult();

		manager.getTransaction().commit();
		return avaliacao;
	}

	
	@SuppressWarnings("unchecked")
	public List<Avaliacao> getAvaliacoesRecurso(Recurso recurso){
		EntityManager manager = getEntityManager();
		
		manager.getTransaction().begin();
        Query query = manager.createQuery("select a from Avaliacao a where a.recurso.idRecurso = :recurso");
		query.setParameter("recurso", recurso.getIdRecurso());

		manager.getTransaction().commit();

		return query.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	public List<Avaliacao> getAvaliacoesRecurso(Recurso recurso, Aprendiz aprendiz){
		EntityManager manager = getEntityManager();
		
		manager.getTransaction().begin();
        Query query = manager.createQuery("select a from Avaliacao a where a.recurso.idRecurso = :recurso and a.aprendiz.idAprendiz = :aprendiz");
		query.setParameter("recurso", recurso.getIdRecurso());
		query.setParameter("aprendiz", aprendiz.getIdAprendiz());

		manager.getTransaction().commit();

		return query.getResultList();
	}
	
	
	 public void salvarAvaliacao(Avaliacao entity) {
	        EntityTransaction tx = getEntityManager().getTransaction();

	        try {
	            tx.begin();
	            getEntityManager().persist(entity);
	            tx.commit();
	
	        } catch (Throwable t) {
	            t.printStackTrace();
	            tx.rollback();
	        }
	    }
	
	/*public void salvar(Avaliacao avaliacao){
		EntityManager manager = getEntityManager();
		
		manager.getTransaction().begin();
		
		
        Query query = manager.createQuery("select a from Avaliacao a where a.recurso.idRecurso = :recurso");
		query.setParameter("recurso", recurso.getIdRecurso());

		manager.getTransaction().commit();

		return query.getResultList();
	}
	*/

}
